//
//  Mahua.m
//  KL
//
//  Created by mac on 15/12/14.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//

#define KLPageCount 500

#import "Mahua.h"
#import "KLDataSaveTool.h"

@implementation Mahua

+ (NSDictionary *)mj_replacedKeyFromPropertyName {
    return @{@"ID" : @"id"};
}

#pragma mark - 截图id的前5位用来做url得拼接
- (NSString *)prefixID {
    return [self.ID substringWithRange:NSMakeRange(0, 5)];
}

#pragma mark - 请求数据
+ (void)mahuaWithUrlString:(NSString *)urlString index:(NSInteger)index page:(NSInteger)page finishedBlock:(finishedBlock)finishedBlock {
    // 请求网络数据 count=%d&page=%d
#warning 尝试修改,可以满足下拉刷新请求数据,但是在存储后来刷新的数据出现了问题,下拉刷新的数据把原来的数据给覆盖了
    NSString *urlStr = [NSString stringWithFormat:@"%@?count=%d&page=%ld", urlString, KLPageCount, page];
    [[ZBNetWorkTool sharedNetWorkTool] GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        KLLog(@"%@", responseObject);
        NSArray *arrayData = (NSArray *)responseObject[@"items"];
        NSArray *data = [self mj_objectArrayWithKeyValuesArray:arrayData context:nil];
        if (arrayData.count == 0) {
            if (finishedBlock) {
                finishedBlock(nil);
            }
            return ;
        }
        // 保存数据
        [KLDataSaveTool saveData:arrayData index:index];
        
        // 把数据传给控制器
        if (finishedBlock) {
            finishedBlock(data);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        KLLog(@"%@", error);
        if (finishedBlock) {
            finishedBlock(nil);
        }
    }];
}

#pragma mark - 在刚开始的时候就去沙盒里获取数据
+ (NSArray *)mahuasWith:(NSInteger)index {
    // 字典数组
    NSArray *array = [KLDataSaveTool dataWith:index];
    if (!array) {
        return nil;
    }
    // 转成模型数组
    return [self mj_objectArrayWithKeyValuesArray:array context:nil];
}

@end
